const mysql = require("../config/mysql");

module.exports = (endpoint) => {
    return async (req, res, next) => {
        const ip = req.ip || req.connection.remoteAddress;
        const WINDOW_SIZE = 60; // 60秒窗口
        const MAX_REQUESTS = 10; // 最大请求数

        try {
            const now = new Date();
            const windowStart = new Date(now.getTime() - WINDOW_SIZE * 1000);

            // 检查或创建速率限制记录
            const [result] = await mysql.query(
                `INSERT INTO rate_limits (ip_address, endpoint, count, window_start)
                    VALUES (?, ?, 1, ?)
                ON DUPLICATE KEY UPDATE count = count + 1`,
                [ip, endpoint, windowStart]
            );

            // 获取当前窗口总请求数
            const [countResult] = await mysql.query(
                `SELECT SUM(count) as total 
                FROM rate_limits 
                WHERE ip_address = ? AND endpoint = ? AND window_start >= ?`,
                [ip, endpoint, windowStart]
            );

            const totalRequests = countResult[0].total || 0;

            if (totalRequests > MAX_REQUESTS) {
                res.setHeader('Retry-After', WINDOW_SIZE);
                return res.status(429).json({
                    error: 'Too many requests',
                    limit: MAX_REQUESTS,
                    remaining: 0,
                    reset: new Date(windowStart.getTime() + WINDOW_SIZE * 1000)
                });
            }

            // 添加速率限制头信息
            res.set({
                'X-RateLimit-Limit': MAX_REQUESTS,
                'X-RateLimit-Remaining': MAX_REQUESTS - totalRequests,
                'X-RateLimit-Reset': Math.floor(windowStart.getTime() / 1000) + WINDOW_SIZE // 使用Unix时间戳
            });

            next();
        } catch (error) {
            console.error('Rate limit error:', error);
            // 出错时放行请求，避免因为限流系统问题导致服务不可用
            next();
        }
    };
};